let loadingCounter = {};

function addLoading(ele = 'body') {
	if (ele) {
		loadingCounter[ele] = loadingCounter[ele] || 0;
		loadingCounter[ele] += 1;
		loadingCounter[ele] === 1 && renderLoading(ele)
	}
}

function removeLoading(ele = 'body') {
	if (ele) {
		loadingCounter[ele] -= 1;
		!loadingCounter[ele] && hideLoading(ele)
	}
}

function renderLoading(ele) {
	if (ele === 'body') {
		uni.showLoading()
	} else {
		const element = document.querySelector(ele);
		if (element) {
			element.innerHTML = '<i class="uni-icon_toast uni-loading"></i>';
		} else {
			loadingCounter[ele] = 0;
		}
	}
}

function hideLoading(ele) {
	if (ele === 'body') {
		uni.hideLoading()
	} else {
		const element = document.querySelector(ele);
		if (document.querySelector(ele)) {
			element.innerHTML = '';
		} else {
			loadingCounter[ele] = 0;
		}
	}
}

const ajax = {
	request: async (url, method, data, formType, ele = 'body') => {
		let token;
		callNative('getToken', '', (data) => {
			token = data;
		});
		addLoading(ele);
		const [error, res] = await uni.request({
			url,
			method: method,
			data,
			header: {
				'blade-auth': decodeURI(uni.getStorageSync('token')) || decodeURI(UrlParam().token),
				'content-type': formType ? 'application/x-www-form-urlencoded' : 'application/json'
			}
		});
		removeLoading(ele);
		if (!error) {
			let {
				data
			} = res;
			return data;
		} else {
			if (process.env.NODE_ENV === "development") {
				alert('请求被拦截，此消息仅在开发环境显示。')
			}
			console.log(error);
		}
	},
	get: (url, data, ele) => {
		return ajax.request(url, 'GET', data, '', ele)
	},
	post: (url, data, ele) => {
		return ajax.request(url, 'POST', data, '', ele)
	},
	upload: async (url, data, ele) => {
		return ajax.request(url, 'POST', data, true, ele)
	}
};
export default ajax;
